package com.young.config;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.util.UUID;

/**
 * @Description: 自定义token
 * @Author: kangyang
 * @Date: 2021/5/8 14:27
 **/
public class TokenSessionMannager extends DefaultWebSessionManager {

    private static final String TOKEN_HEADER_NAME = "Authorization";

    private static final String TOKEN_COOKIE_NAME = "JSESSIONID";

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String token = WebUtils.toHttp(request).getHeader(TOKEN_HEADER_NAME);
        if(StringUtils.isEmpty(token) || "null".equals(token)) {
            HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
            List<Cookie> cookies = new ArrayList<>();
            if(httpServletRequest != null && httpServletRequest.getCookies() != null) {
                cookies = Arrays.asList(WebUtils.toHttp(request).getCookies());
                if(CollectionUtils.isNotEmpty(cookies)) {
                    List<Cookie> jsessinoCookies = cookies.stream()
                        .filter(cookie -> cookie != null && TOKEN_COOKIE_NAME.equals(cookie.getName())).collect(
                            Collectors.toList());
                    if(CollectionUtils.isNotEmpty(jsessinoCookies)) {
                        Cookie cookie = jsessinoCookies.get(0);
                        token = cookie.getValue();
                    }
                }else {
                    token = UUID.randomUUID().toString();
                }
            }
        }
        return token;
    }
}
